﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using UniRlv.COL;
using UniRlv.UI.Main.WarerHourseIn;
using UniRlv.UI.Main.Widget;
using UniRlv.Utility;
using System.Linq;

namespace UniRlv.UI.Main.DataManage
{
    public partial class FrmTaskData : UniRlv.UI.Main.FrmBase
    {
        FrmProcessBar progBar = null;
        int checkQty = 50;

        public FrmTaskData()
        {
            InitializeComponent();
        }

        private void FrmTaskData_Load(object sender, EventArgs e)
        {
            UIHelper.InitDataGridView(dgvDetails);
            dgvDetails.MultiSelect = true;
            lstCdt.SelectedIndex = 0;

            toolBtnQuery.Visible = true;
            toolBtnQuery.Click += toolBtnQuery_Click;

            toolBtnExport.Visible = true;
            toolBtnExport.Click += toolBtnExport_Click;

            ToolStripButton btnRunTask = AddToolButton("RunTask", "启动任务");
            btnRunTask.Click += btnRunTask_Click;

            checkQty = ConfigurationHelper.AppGetInt("checkDataQty");

            //panelBatch.Controls.Remove(panelDate);
            //panelBatch.Controls.Remove(panelOther);

            //panelDate.Controls.Remove(panelBatch);
            //panelDate.Controls.Remove(panelOther);

            //panelOther.Controls.Remove(panelDate);
            //panelOther.Controls.Remove(panelBatch);

            panelOther.Size = panelBatch.Size;
            panelOther.Location = panelBatch.Location;

            panelDate.Size = panelBatch.Size;
            panelDate.Location = panelBatch.Location;
        }

        private void btnRunTask_Click(object sender, EventArgs e)
        {
            if (dgvDetails.RowCount == 0 || dgvDetails.CurrentRow == null)
            {
                MessageBox.Show("请先选择需要启动的任务！");
            }
            else
            {
                if (WorkSpace.GetInstance().IfTaskFree())
                {

                    ProductionTask t = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;

                    string msg = string.Empty;

                    List<PrintInfo> li = DALOpr.Query<PrintInfo>("taskID = " + t.ID, ref msg);

                    if (MessageBox.Show(this, "确定需要启动该任务：" + t.ToString(), "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                    {
                        int nSel = ConfigurationHelper.AppGetInt("dupCheckType");
                        if (nSel == 1)
                        {
                            if (!File.Exists(t.extendInfo))
                            {
                                MessageBox.Show("查重数据源文件不存在，请重新指定，避免入库失败！");
                            }
                        }

                        PublicObject.CurTask = t;
                        PublicObject.CurPrintInfos = li;

                        msg = string.Empty;
                        PublicObject.CurLine = DALOpr.QuerySingle<ProductionLine>("select * from ProductionLine where id=" + t.lineID, ref msg);

                        this.backgroundWorker1.RunWorkerAsync(nSel); // 运行 backgroundWorker 组件

                        progBar = new FrmProcessBar(this.backgroundWorker1);// 显示进度条窗体
                        progBar.Text = "加载任务信息";
                        progBar.ShowDialog(this);
                    }
                }
                else
                {
                    MessageBox.Show("当前有生产任务正忙，无法再启动新任务");
                    return;
                }
            }
        }

        private void toolBtnExport_Click(object sender, EventArgs e)
        {
            if (dgvDetails.RowCount == 0 || dgvDetails.CurrentRow == null)
            {
                MessageBox.Show("无数据可导出，先选择需要到处的纪录！");
            }
            else
            {
                ProductionTask t = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;
                string nameRule = ConfigurationHelper.AppGetString("outputInFileName");
                if (string.IsNullOrEmpty(nameRule))
                {
                    nameRule = $"InData_{t.batch}_一级码{t.scanQuantity}条_{DateTime.Now.ToString("yyyyMMdd-HHmmss")}";
                }
                string err = "";
                ProductInfo pi = DALOpr.QueryByID<ProductInfo>(t.productID.ToString(), ref err);

                if (pi != null)
                {
                    nameRule = nameRule.Replace("{itemid}", pi.itemid);
                    nameRule = nameRule.Replace("{spm}", pi.spm);
                }

                nameRule = nameRule.Replace("{qty}", t.scanQuantity.ToString());
                nameRule = nameRule.Replace("{batch}", t.batch);
                nameRule = nameRule.Replace("{unit}", t.minTagUnit);
                nameRule = nameRule.Replace("{taskid}", t.ID.ToString());
                nameRule = nameRule.Replace("{tym}", t.tym);
                nameRule = nameRule.Replace("{gg}", t.gg);
                nameRule = nameRule.Replace("{now}", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
                nameRule = nameRule.Replace("{taskNO}", t.number.ToString());

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.AddExtension = true;
                sfd.DefaultExt = "xml";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                sfd.FileName = string.Format("{0}.xml", nameRule);
                sfd.Filter = "(*.xml)XML文件|*.xml";
                sfd.Title = "导出入库文件";

                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string msg = string.Empty;
                    this.Cursor = Cursors.WaitCursor;
                    #region 入库文件还需分割
                    //try
                    //{
                    //    XmlDocument doc = FrmDataDeal.GenInXmlHead(t, t.produceDate, DateTime.Now);

                    //    if (doc != null)
                    //    {
                    //        //查询数据
                    //        string whereString = string.Format(" taskID='{0}' and stationNumber=1 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                    //        List<CodeInfo> codes1 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                    //        whereString = string.Format(" taskID='{0}' and stationNumber=2 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                    //        List<CodeInfo> codes2 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                    //        whereString = string.Format(" taskID='{0}' and stationNumber=3 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                    //        List<CodeInfo> codes3 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                    //        whereString = string.Format(" taskID='{0}' and stationNumber=4 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                    //        List<CodeInfo> codes4 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                    //        int[] ratios = AppHelper.GetLevelRatios(t.tagRatio);
                    //        int ratio32 = 0, ratio21 = 0, ratio43 = 0;

                    //        switch (t.tagLevel)
                    //        {
                    //            case 1:
                    //                FrmDataDeal.SaveCode1(doc, codes1.ConvertAll(s => s.code));
                    //                break;
                    //            case 2:
                    //                ratio21 = ratios[0];
                    //                FrmDataDeal.SaveCode12(doc, ratio21, codes1.ConvertAll(s => s.code), codes2.ConvertAll(s => s.code));
                    //                break;
                    //            case 3:
                    //                ratio32 = ratios[0];
                    //                ratio21 = ratios[1];
                    //                FrmDataDeal.SaveCode123(doc, ratio21, ratio32, codes1.ConvertAll(s => s.code),
                    //                    codes2.ConvertAll(s => s.code), codes3.ConvertAll(s => s.code));
                    //                break;
                    //            case 4:
                    //                ratio43 = ratios[0];
                    //                ratio32 = ratios[1];
                    //                ratio21 = ratios[2];
                    //                FrmDataDeal.SaveCode1234(doc, ratio21, ratio32, ratio43, codes1.ConvertAll(s => s.code),
                    //                    codes2.ConvertAll(s => s.code), codes3.ConvertAll(s => s.code), codes4.ConvertAll(s => s.code));
                    //                break;
                    //            default:
                    //                ShowErrorMessageBox("出现错误", "包装级别不支持：级别=" + t.tagLevel);
                    //                return;

                    //        }

                    //        using (StreamWriter sw = new StreamWriter(sfd.FileName))
                    //        {
                    //            XmlWriterSettings settings = new XmlWriterSettings();
                    //            settings.Indent = true;
                    //            settings.IndentChars = "  ";
                    //            XmlWriter xmlWriter = XmlWriter.Create(sw, settings);
                    //            doc.Save(xmlWriter);
                    //            xmlWriter.Close();

                    //            t.exportTimes++;

                    //            Dictionary<string, object> dict = new Dictionary<string, object>();
                    //            dict.Add("state", (int)task_state.TS_EXPORTED);
                    //            dict.Add("scanQuantity", t.exportTimes.ToString());
                                

                    //            string sql = EntityHelper.GetUpdateSql(t);
                    //            msg = string.Empty;

                    //            DALOpr.ExecuteNonQuery(sql, ref msg);

                    //            MessageBox.Show(this, "导出完成！", "提示！");
                    //        }
                    //    }
                    //    else
                    //    {
                    //        ShowErrorMessageBox("出现错误", msg);
                    //    }
                    //}
                    //catch (Exception exp)
                    //{

                    //    ShowErrorMessageBox("出现错误", exp.Message);
                    //}
                    #endregion

                    #region 入库文件导出并自动分割
                    try
                    {
                        //查询数据
                        string whereString = string.Format(" taskID='{0}' and stationNumber=1 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                        List<CodeInfo> codes1 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                        whereString = string.Format(" taskID='{0}' and stationNumber=2 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                        List<CodeInfo> codes2 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                        whereString = string.Format(" taskID='{0}' and stationNumber=3 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                        List<CodeInfo> codes3 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                        whereString = string.Format(" taskID='{0}' and stationNumber=4 and (codeState=1 or codeState=2) order by serialNumber", t.ID);
                        List<CodeInfo> codes4 = DALOpr.Query<CodeInfo>(whereString, ref msg);

                        int[] ratios = AppHelper.GetLevelRatios(t.tagRatio);
                        int ratio32 = 0, ratio21 = 0, ratio43 = 0;

                        switch (t.tagLevel)
                        {
                            case 1:
                                break;
                            case 2:
                                ratio21 = ratios[0];
                                break;
                            case 3:
                                ratio32 = ratios[0];
                                ratio21 = ratios[1];

                                break;
                            case 4:
                                ratio43 = ratios[0];
                                ratio32 = ratios[1];
                                ratio21 = ratios[2];
                                break;
                            default:
                                ShowErrorMessageBox("出现错误", "包装级别不支持：级别=" + t.tagLevel);
                                return;

                        }

                        //父码必数量必须可以涵盖子码

                        InFileGenAndSplit ifgs = new InFileGenAndSplit();
                        ifgs.codes1 = codes1.ConvertAll(s => s.code);
                        ifgs.codes2 = codes2.ConvertAll(s => s.code);
                        ifgs.codes3 = codes3.ConvertAll(s => s.code);
                        ifgs.codes4 = codes4.ConvertAll(s => s.code);
                        ifgs.Path2Save = sfd.FileName;
                        ifgs.ratio21 = ratio21;
                        ifgs.ratio32 = ratio32;
                        ifgs.ratio43 = ratio43;
                        ifgs.tmOpr = DateTime.Now;
                        ifgs.tmProduce = t.produceDate;
                        ifgs.task = t;
                        bool bOK = ifgs.SaveInFile();
                        msg = ifgs.ErrorString;


                        if (bOK)
                        {
                            t.exportTimes++;

                            Dictionary<string, object> dict = new Dictionary<string, object>();
                            dict.Add("state", (int)task_state.TS_EXPORTED);
                            dict.Add("scanQuantity", t.exportTimes.ToString());


                            string sql = EntityHelper.GetUpdateSql(t);
                            msg = string.Empty;

                            DALOpr.ExecuteNonQuery(sql, ref msg);

                            MessageBox.Show(this, "导出完成！", "提示！");
                        }
                        else
                        {
                            ShowErrorMessageBox("出现错误", msg);
                        }
                    }
                    catch (Exception exp)
                    {

                        MessageBox.Show(this, msg, "出现错误:" + exp.Message);
                    }
                    #endregion

                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void toolBtnQuery_Click(object sender, EventArgs e)
        {
            string whereString = " ";
            string msg = string.Empty;

            if (lstCdt.SelectedIndex == 2)
            {//根据条码查询
                CodeInfo code = DALOpr.QuerySingle<CodeInfo>("select * from codeinfo where code='" + txtOther.Text + "'", ref msg);

                if (code == null)
                {
                    MessageBox.Show("查询出错：" + msg);
                    return;
                }
                else
                {
                    whereString += string.Format("id = {0}", code.taskID);
                }
            }
            else
            {
                if (lstCdt.SelectedIndex == 0)
                {
                    //whereString += string.Format("batch LIKE '%{0}%' and tym like '%{1}%' and spm like '%{2}%'", txtBatch.Text, txtTym.Text, txtSpm.Text);
                    whereString += string.Format("batch LIKE '%{0}%' and spm like '%{1}%' and number like '%{2}%'", txtBatch.Text, txtSpm.Text, txtTaskNO.Text);
                }

                if (lstCdt.SelectedIndex == 1)
                {
                    whereString += string.Format(" createTime >= '{0}' and createTime <= '{1}'", dtpFrom.Value.ToString("yyyy-MM-dd 00:00:00"), dtpTo.Value.ToString("yyyy-MM-dd 23:59:59"));
                }

                if (lstCdt.SelectedIndex == 3)
                {//审核人
                    whereString += string.Format("verifyer LIKE '%{0}%'", txtOther.Text);
                }

                if (lstCdt.SelectedIndex == 4)
                {//任务编码
                    whereString += string.Format("number LIKE '%{0}%'", txtOther.Text);
                }
            }

            

            List<ProductionTask> li = DALOpr.Query<ProductionTask>(whereString, ref msg);

            if (string.IsNullOrEmpty(msg))
            {

                dgvDetails.DataSource = li;

                lbQueryTip.Text = string.Format("查询到{0}条记录，一级码扫描数量累计{1}个", li.Count, li.Sum(s1=>s1.scanQuantity));
            }
            else
            {
                dgvDetails.DataSource = null;
                lbQueryTip.Text = string.Format("查询到0条记录，一级码扫描数量累计0个");
                MessageBox.Show("查询出错：" + msg);
            }
        }

        private void lstCdt_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstCdt.SelectedIndex == 2 || lstCdt.SelectedIndex == 3 || lstCdt.SelectedIndex == 4)
            {
                panelOther.Visible = true;
                panelDate.Visible = false;
                panelBatch.Visible = false;
            }
            else if(lstCdt.SelectedIndex == 0)
            {
                panelBatch.Visible = true;
                panelDate.Visible = false;
                panelOther.Visible = false;
            }
            else if(lstCdt.SelectedIndex == 1)
            {
                panelBatch.Visible = false;
                panelDate.Visible = true;
                panelOther.Visible = false;
            }
        }

        public override void OnScanCode(string orgCode, string validCode)
        {
            txtBatch.Text = validCode;
            toolBtnQuery.PerformClick();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string msg = string.Empty;
            int nType = Convert.ToInt32(e.Argument);
            List<CodeInfo> li = new List<CodeInfo>();

            if (nType == 0)
            {
                //加载历史扫描数据
                worker.ReportProgress(0, "加载历史数据....\r\n");

                //string whereString = string.Format(" (codeState=1 or codeState=2) ");

                //int cnt = Convert.ToInt32(DALOpr.RawGetScalar("select count(id) from codeinfo where" + whereString, ref msg));
                //List<CodeInfo> li = new List<CodeInfo>();
                //int pages = cnt == 0 ? 0 : (cnt - 1) / 10000 + 1;

                //if (pages > 0)
                //{
                //    //最多加载checkQty万

                //    for (int i = 1; i <= pages && i <= checkQty; i++)
                //    {
                //        li.AddRange(DALOpr.QueryPage<CodeInfo>(i, 10000, ref msg));
                //        worker.ReportProgress(i * 95 / pages, ".");
                //    }
                //}
                //else
                //{
                //    worker.ReportProgress(94, "加载历史数据完成");
                //}


                int cnt = Convert.ToInt32(DALOpr.RawGetScalar("SELECT count(a.id) FROM [CodeInfo] a join ProductionTask b on a.taskID=b.id where b.productID = " + PublicObject.CurTask.productID, ref msg));
                
                int pages = cnt == 0 ? 0 : (cnt - 1) / 10000 + 1;

                if (pages > 0)
                {
                    //最多加载checkQty万
                    for (int i = 1; i <= pages && i <= checkQty; i++)
                    {
                        li.AddRange(DALOpr.QueryCodeHistoryPageByProduct(i, 10000, PublicObject.CurTask.productID, ref msg));
                        worker.ReportProgress(i * 94 / pages, ".");
                    }
                }
                else
                {
                    worker.ReportProgress(93, "加载历史数据完成.\r\n");
                }

                PublicObject.CodeScanned.AddRange(li.ConvertAll<string>(s => s.code));
            }
            else if (nType == 1)
            {
                worker.ReportProgress(0, "加载查重数据源...\r\n");
                string[] lines = File.ReadAllLines(PublicObject.CurTask.extendInfo, Encoding.UTF8);

                string code24BIt = "";
                foreach (var item in lines)
                {
                    if (AppHelper.SYZSGet24BitFromCode(ref code24BIt, item, 2))
                    {
                        PublicObject.CodeValid.Add(item);
                    }
                }

                if (PublicObject.CodeValid.Count == 0)
                {
                    string err = "无合法的数据可查重";
                    //worker.ReportProgress(100, "加载失败：" + err);
                    e.Result = "加载失败：" + err;
                    return;
                }
            }
           else
            {//不查重
                CodePrcUtility.DUP_CHECK = false;
            }

            //加载关联数据 
            FrmMain.GetInstance().lastRltCodeLoadTime = DateTime.Now;

            string whereString = $" batch='{PublicObject.CurTask.batch}' and inTime<='{FrmMain.GetInstance().lastRltCodeLoadTime.ToString("yyyy-MM-dd HH:mm:ss")}' and pzwh='{PublicObject.CurTask.pzwh}'";
            worker.ReportProgress(94, "加载关联码....\r\n");

            List<CodeRltInfo> rss = DALOpr.Query<CodeRltInfo>(whereString, ref msg);

            if (rss != null && rss.Count > 0)
            {
                PublicObject.CodeRlt.AddRange(rss);
            }

            

            //加载数据
            worker.ReportProgress(95, "加载一级码....\r\n");
            whereString = string.Format(" taskID='{0}' and stationNumber=1 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            li = DALOpr.Query<CodeInfo>(whereString, ref msg);

            PublicObject.arrCode1.Clear();
            PublicObject.arrCode1.GetList(1).AddRange(li.FindAll((t) => { return t.subDeviceNumber != 0; }));
            PublicObject.arrCode1.GetList(0).AddRange(li.FindAll((t) => { return t.subDeviceNumber == 0; }));
            //PublicObject.arrCode1.GetList(0).AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 1 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            //PublicObject.arrCode1.GetList(1).AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 1 && t.subDeviceNumber != 0; }).OrderBy(c => c.serialNumber));
            
            worker.ReportProgress(96, "加载一级码完成，加载二级码....\r\n");


            whereString = string.Format(" taskID='{0}' and stationNumber=2 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode2 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode2.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 2 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(97, "加载二级码完成，加载三级码....\r\n");

            whereString = string.Format(" taskID='{0}' and stationNumber=3 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode3 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode3.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID && t.stationNumber == 3 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(98, "加载三级码完成，加载四级码....\r\n");

            whereString = string.Format(" taskID='{0}' and stationNumber=4 and (codeState=1 or codeState=2) order by serialNumber", PublicObject.CurTask.ID);
            PublicObject.arrCode4 = DALOpr.Query<CodeInfo>(whereString, ref msg);
            //PublicObject.arrCode4.AddRange(li.FindAll((t) => { return t.taskID == PublicObject.CurTask.ID  && t.stationNumber == 4 && t.subDeviceNumber == 0; }).OrderBy(c => c.serialNumber));
            worker.ReportProgress(99, "加载四级码完成，启动任务....\r\n");

            if (WorkSpace.GetInstance().RunTask())
            {
                worker.ReportProgress(100, "启动任务完成！");
            }
            else
            {
                string err = WorkSpace.GetInstance().ErrorString;
                worker.ReportProgress(100, "启动失败：" + err);
                e.Result = err;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progBar.Close();

            if (e.Result != null)
            {
                PublicObject.CurTask = null;
                MessageBox.Show(e.Result.ToString());
            }
            else if (e.Cancelled)
            {
                MessageBox.Show("操作取消");
            }
            else
            {
                FrmMain.GetInstance().SwitchFormByModuleName("WarehourseInStatus");
            }
        }

        private void txtOther_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolBtnQuery.PerformClick();
            }
        }

        private void menuArchieve_Click(object sender, EventArgs e)
        {
            if (dgvDetails.SelectedRows == null || dgvDetails.SelectedRows.Count == 0)
            {
                ShowInfoMessageBox("提示", "先选择需要归档的记录！");
            }
            else
            {
                if (ShowConfirmDialog("请确认", "归档数据后将生产任务及其数据归档到历史数据库中，无法再启动生产，确认继续？") == DialogResult.OK)
                {
                    this.Cursor = Cursors.WaitCursor;

                    List<string> ids = new List<string>();
                    string msg = string.Empty;

                    foreach (DataGridViewRow item in dgvDetails.SelectedRows)
                    {
                        ProductionTask t = item.DataBoundItem as ProductionTask;

                        ids.Add(t.ID.ToString());
                    }



                    if (DALOpr.BKTasks(ids, ref msg))
                    {
                        toolBtnQuery.PerformClick();
                        ShowInfoMessageBox("提示", "归档完成！");
                    }
                    else
                    {
                        ShowErrorMessageBox("出现错误", "归档失败：" + msg);
                    }

                    this.Cursor = Cursors.Default;
                }

            }
        }

        private void menuPrint_Click(object sender, EventArgs e)
        {
            if (dgvDetails.SelectedRows == null || dgvDetails.SelectedRows.Count == 0)
            {
                ShowInfoMessageBox("提示", "先选择需要打印的记录！");
                return;
            }

            if (dgvDetails.SelectedRows.Count>1)
            {
                ShowInfoMessageBox("提示", "只能选择一条记录打印！");
                return;
            }

            FrmPrintParameter frm = new FrmPrintParameter();
            frm.PrintQty = 1;
            frm.PrintStation = 3;

            if (frm.ShowDialog() == DialogResult.OK)
            {
                ProductionTask t = dgvDetails.CurrentRow.DataBoundItem as ProductionTask;
                string msg = string.Empty;

                this.Cursor = Cursors.WaitCursor;

                if (WorkSpace.GetInstance().PrintTest(t, frm.PrintStation, frm.PrintQty, ref msg))
                {
                    ShowInfoMessageBox("提示", "打印完成！");
                }
                else
                {
                    ShowErrorMessageBox("出现错误", "打印失败：" + msg);
                }

                this.Cursor = Cursors.Default;
            }

        }

        private void menuExport_Click(object sender, EventArgs e)
        {
            toolBtnExport.PerformClick();
        }

        private void menuRunTask_Click(object sender, EventArgs e)
        {
            btnRunTask_Click(this, null);
        }
    }
}
